import { create } from 'zustand'
import { login as loginApi, logout as logoutApi } from '../utils/request'

export const useUserStore = create((set, get) => ({
  // 用户信息
  userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
  // 登录状态
  isLoggedIn: !!localStorage.getItem('token'),
  // 登录加载状态
  loginLoading: false,

  // 设置用户信息
  setUserInfo: (userInfo) => {
    set({ userInfo })
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  },

  // 设置登录状态
  setIsLoggedIn: (isLoggedIn) => {
    set({ isLoggedIn })
  },

  // 登录
  login: async (loginData) => {
    set({ loginLoading: true })
    try {
      const response = await loginApi(loginData)
      const { token, ...userInfo } = response.data
      
      // 保存 token 和用户信息
      localStorage.setItem('token', token)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      
      set({ 
        userInfo, 
        isLoggedIn: true, 
        loginLoading: false 
      })
      
      return response
    } catch (error) {
      set({ loginLoading: false })
      throw error
    }
  },

  // 登出
  logout: async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      // 清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      set({ 
        userInfo: {}, 
        isLoggedIn: false 
      })
    }
  },

  // 清除用户状态
  clearUserState: () => {
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    set({ 
      userInfo: {}, 
      isLoggedIn: false 
    })
  }
}))
